﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;

namespace QLNH
{
    //listview comparer
    public class ListViewItemComparer : IComparer
    {
        private int _column;
        public int Column
        {
            get { return _column; }
            set { _column = value; }
        }

        private bool _numeric;
        public bool Numeric
        {
            get { return _numeric; }
            set { _numeric = value; }
        }

        private SortOrder _orderOfSort = SortOrder.Ascending;
        public SortOrder OrderOfSort
        {
            get { return _orderOfSort; }
            set { _orderOfSort = value; }
        }

        public ListViewItemComparer(int colIndex)
        {
            Column = colIndex;
        }

        public int Compare(object x, object y)
        {
            ListViewItem liX = (ListViewItem)x;
            ListViewItem liY = (ListViewItem)y;

            if (Numeric)
            {
                decimal liXVal, liYVal;
                try
                {
                    liXVal = Decimal.Parse(liX.SubItems[Column].Text);
                }
                catch
                {
                    liXVal = 0;
                }

                try
                {
                    liYVal = Decimal.Parse(liY.SubItems[Column].Text);
                }
                catch
                {
                    liYVal = 0;
                }

                if (OrderOfSort == SortOrder.Ascending)
                    return Decimal.Compare(liXVal, liYVal);
                else if (OrderOfSort == SortOrder.Descending)
                {
                    return -Decimal.Compare(liXVal, liYVal);
                }
                else
                    return 0;
            }
            else
            {
                string liXText = liX.SubItems[Column].Text;
                string liYText = liY.SubItems[Column].Text;

                if (OrderOfSort == SortOrder.Ascending)
                    return String.Compare(liXText, liYText);
                else if (OrderOfSort == SortOrder.Descending)
                {
                    return -String.Compare(liXText, liYText);
                }
                else
                    return 0;
            }
        }
    }
}
